﻿using DoNet.Common.Enums;
using DoNet.Email;
using DoNet.Email.Entity;
using DoNet.Handlers.Commands;
using DoNet.Quartz.Jobs.Common;
using DoNet.System.IServices;
using DoNet.System.Models;
using MediatR;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System.Diagnostics;

namespace DoNet.Quartz.Jobs
{
    /// <summary>
    /// 定时删除操作日志和任务日志
    /// </summary>
    [DisallowConcurrentExecution]
    public class SysLogJob : IJob
    {
        private readonly ITaskManagerService taskManagerService;
        private readonly ITaskJobsLogService taskJobsLogService;
        private readonly ILogService logService;
        private IMediator mediator;

        public SysLogJob(ITaskManagerService _taskManagerService, ITaskJobsLogService _taskJobsLogService, ILogService _logService, IMediator _mediator)
        {
            taskManagerService = _taskManagerService;
            taskJobsLogService = _taskJobsLogService;
            logService = _logService;
            mediator = _mediator;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            DateTime dateTime = DateTime.Now;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            var trigger = (context as JobExecutionContextImpl)?.Trigger as AbstractTrigger;
            if (trigger != null)
            {
                TaskManager taskManager = await taskManagerService.GetByWhereAsync("Id=@PrimaryKey and GroupName=@GroupName", new { PrimaryKey = trigger.Name, GroupName = trigger.Group });
                if (taskManager != null)
                {
                    try
                    {
                        string msg = $"开始时间:{dateTime.ToString("yyyy-MM-dd HH:mm:ss ffff")}";
                        //记录任务执行记录
                        await taskManagerService.RecordRunAsync(taskManager.Id, JobAction.开始, true, msg);
                        //初始化任务日志
                        FileQuartz.InitTaskJobLogPath(taskManager.Id);

                        var jobId = context.MergedJobDataMap.GetString("OpenJob");
                        taskJobsLogService.ClearLog();
                        await logService.DeleteByWhereAsync("CreatorTime<@CreatorTime", new { CreatorTime = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd") });

                        stopwatch.Stop();
                        string resume = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n";
                        await taskManagerService.RecordRunAsync(taskManager.Id, JobAction.结束, true, resume);
                        if ((NoticeType)taskManager.SendMail == NoticeType.All)
                        {
                            if (!string.IsNullOrEmpty(taskManager.EmailAddress))
                            {
                                List<string> recipients = new List<string>();
                                recipients = taskManager.EmailAddress.Split(",").ToList();
                                var mailBodyEntity = new MailBodyEntity()
                                {
                                    Body = resume + ",请勿回复本邮件",
                                    Recipients = recipients,
                                    Subject = taskManager.TaskName
                                };

                                SendMailCommand sendMailCommand = new SendMailCommand(mailBodyEntity);
                                await mediator.Send(sendMailCommand);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        stopwatch.Stop();
                        string resume = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n";
                        await taskManagerService.RecordRunAsync(taskManager.Id, JobAction.结束, true, resume, ex.Message);
                        FileQuartz.WriteErrorLog(ex.Message);
                        if ((NoticeType)taskManager.SendMail == NoticeType.Error || (NoticeType)taskManager.SendMail == NoticeType.All)
                        {
                            if (!string.IsNullOrEmpty(taskManager.EmailAddress))
                            {
                                List<string> recipients = new List<string>();
                                recipients = taskManager.EmailAddress.Split(",").ToList();
                                var mailBodyEntity = new MailBodyEntity()
                                {
                                    Body = "处理失败," + ex.Message + ",请勿回复本邮件",
                                    Recipients = recipients,
                                    Subject = taskManager.TaskName
                                };
                                await SendMailHelper.SendMail(mailBodyEntity);
                            }
                        }
                    }
                }
                else
                {
                    FileQuartz.WriteErrorLog($"任务不存在");
                }
            }
        }
    }
}
